package com.atguigu.yuntai.govern.parser;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.antlr.runtime.tree.Tree;

import java.util.List;

/**
 * 解析语法树，将sql语句拆成多个对象
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FieldObj {

    public String tableAlias;

    public String tableName;

    public String tableNameOrAlias;

    public String fieldName;

    public FieldObj(Tree tree, List<TableObj> tableObjList) {
        if (tree.getChild(0).getText().equals("TOK_TABLE_OR_COL")) {
            tableNameOrAlias = tree.getChild(0).getChild(0).getText();
            fieldName = tree.getChild(1).getText();
        } else {
            fieldName = tree.getChild(0).getText();
        }

        if (tableNameOrAlias != null && tableNameOrAlias.length() > 0 && tableObjList != null && tableObjList.size() > 0) {
            for (TableObj tableObj : tableObjList) {
                if (tableNameOrAlias.equals(tableObj.getTableName())) {
                    tableName = tableObj.getTableName();
                } else if (tableNameOrAlias.equals(tableObj.getTableAlias())) {
                    tableName = tableObj.getTableName();
                    tableAlias = tableObj.getTableAlias();
                }
            }

        }

    }

    public FieldObj(Tree tree) {
        this(tree, null);
    }
}
